package com.joca.scheduling.pages;

import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;

import com.joca.scheduling.database.UserData;
import com.joca.scheduling.entities.Role;
import com.joca.scheduling.entities.User;
import com.joca.scheduling.hibernateservices.UserServiceHibernate;

public class Index {
	private String userName;
	private String password;
	@SessionState(create = false)
	@Property
	private User user;
	private boolean userExists;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	Object onActivate() {
		Class nextPage = null;
		if (userExists) {
			if (user.getRole() == Role.Professor) {
				nextPage = Professor.class;
			}
			if (user.getRole() == Role.Student) {
				nextPage = Student.class;
			}
		}
		return nextPage;
	}

	@OnEvent
	Object onFormSubmit() {
		Class nextPage = null;
		User authenticatedUser = null;
		authenticatedUser = authenticate(userName, password);
		if (authenticatedUser != null) {
			if (authenticatedUser.getRole() == Role.Professor) {
				user = authenticatedUser;
				nextPage = Professor.class;
			} else {
				user = authenticatedUser;
				nextPage = Student.class;
			}
		} else {
			System.out.println("aaaaaaaaaaaaaaa");
			nextPage = null;
		}
		return nextPage;
	}

	private User authenticate(String userName, String password) {
		User us = new User();
		us.setUsername(userName);
		us.setPassword(password);
		return UserServiceHibernate.getUserServiceHibernate().logIn(us);
		// return UserData.getInstance().logIn(us);

	}

}
